package com.ftg.learn.chapter14;


import java.sql.*;
import java.util.Objects;

/**
 * 学习一下json在jdbc当中的使用
 * JSON : js 对象简谱
 * javascript object Notation
 * <p>
 * json :
 * [] 数组 ,
 * {} key:value,key:value
 * 转义符号 \t \n
 * "[{\"name\":"张三","age":"23"},{"name":"李四","age":"23"}]"
 * <p>
 * StringBuilder  速度
 * jdbc加载驱动 mysql 8 省略
 * mysql5.7
 * 第一种 反射
 * Class.forName("com.mysql.cj.jdbc.Driver");
 * 第二种 注册
 * DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/3/7 下午2:23
 */
public class LearnJdbc06Json01 {

    public static void main(String[] args) {
        LearnJdbc06Json01 l = new LearnJdbc06Json01();
        System.out.println(l.queryForJson("select * from student"));
    }

    /**
     * 用于处理生成json的方法，做dql
     *
     * @param sql  sql
     * @param para para
     * @return String
     */
    public String queryForJson(String sql, Object... para) {
        StringBuilder result = new StringBuilder("[");
        try (
                Connection conn = DriverManager.getConnection(JdbcConst.URL, JdbcConst.USERNAME, JdbcConst.PASSWORD);
                PreparedStatement pstmt = conn.prepareStatement(sql)
        ) {

            if (Objects.nonNull(para)) {
                for (int i = 0; i < para.length; i++) {
                    pstmt.setObject(i + 1, para[i]);
                }
            }

            ResultSet rs = pstmt.executeQuery();

            ResultSetMetaData metaData = rs.getMetaData();
            while (rs.next()) {
                StringBuilder temp = new StringBuilder("{");
                for (int i = 0; i < metaData.getColumnCount(); i++) {
                    temp.append("\"").append(metaData.getColumnName(i + 1).toLowerCase()).append("\"")
                            .append(" : ")
                            .append("\"")
                            .append(rs.getObject(i + 1) == null ? "": rs.getObject(i + 1).toString())
                            .append("\"")
                            .append( i == metaData.getColumnCount() - 1 ? "" : ",");
                }
                temp.append("}");
                result.append(temp).append(",");
            }


        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result.toString().endsWith(",") ? result.substring(0,result.length()-1)+"]":result+"]";
    }

//    sun net.sf json
//    google gson
//    alibaba fastjson  fastjson2
//    spring jackson
}
